<?php

/**
 * 公共方法集合
 */
class Common
{
    /**
     * 请求服务器API返回数据
     * 
     * @param string    $url        
     * @param array     $params
     * @return array
     */
    public static function callMethod( $url, $params = array() ) 
    {
        if( isset( $params['avatar'] ) )
        {
            $postParams['avatar'] = $params['avatar'];
            unset( $params['avatar'] );
        }
        
        if( isset( $params['bgImg'] ) )
        {
            $postParams['bgImg'] = $params['bgImg'];
            unset( $params['bgImg'] );
        }
        
        if( isset( $params['img'] ) )
        {
            $postParams['img'] = $params['img'];
            unset( $params['img'] );
        }
        
        $postParams['data'] = json_encode( $params );
        //$url .= '&data=' . $postParams['data'];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'API PHP Client' );
        $result = curl_exec($ch);
        $errno = curl_errno($ch);
        curl_close($ch);
        
        $destResult = (array)json_decode( $result , true );
               
        if( !empty( $destResult ) )
        {
            $destResult['url'] = $url;
            return (array)$destResult;
        }

        return array( $result , 'url' => $url );
    }
    
    /**
     * 合成参数返回API请求地址
     * 
     * @param type $params 
     */
    public static function getApiUrl( $method = array() , $uId = 0 )
    {
        $systemConfig = self::getConfig();
        if( empty( $systemConfig['serverAddr'] ) )
        {
            return false;
        }
        return $systemConfig['serverAddr'] . "?uId={$uId}&con={$method[0]}&act={$method[1]}&err=1";
    }
    
    /**
	 * @brief	返回测试相关配置信息
	 * @param	$key	配置文件项
	 * @return 	Array
	 */
	public static function & getConfig( $key = '' )
	{
             
               static $config = array();
		if( empty( $config ) )
		{
			if( file_exists( TEST_CONFIG_DIR . "/SystemConfig.php" ) )
			{
                           
				$config = require( TEST_CONFIG_DIR . "/SystemConfig.php" );
			}
		}
		
		if( !isset( $config[$key] ) )
		{
                         $key = str_replace( 'Config', '', $key );
            
                        if( strpos( $key , '_' ) !== false )
                        {
                            $key = str_replace( '_', '/', $key );
                        }
                
			if( file_exists( TEST_CONFIG_DIR . "/{$key}Config.php" ) )
			{
				$config[$key] = require( TEST_CONFIG_DIR . "/{$key}Config.php" );
			}
		}
		
		if( $key )
		{
		    return $config[$key];
		}
		
		return $config;
	}
    
    /**
	 * 获取Cache实例
	 * @param	string $param	Cache服务器名称
	 * @return	Core_Cache_Memcached
	 */
	public static function & getCache( $param = 'data' )
	{
		static $cache = array();
		if( empty( $cache[$param] ) )
		{
			$config = self::getConfig( 'memcache' );
			if( empty( $config[$param] ) )
			{
				throw new AppException( 1 , 'memcache\\' . $param );
			}
			else
			{
				$memcacheClass = 'Helper_Cache_' . self::getConfig( 'memcacheClass' );
				$cache[$param] = new $memcacheClass( $config[$param] );
			}
		}
		
		return $cache[$param];
	}
    
	/**
	 * 根据数据库名获取数据库
	 *
	 * @param string $dbName
	 * @return Helper_MysqlDb
	 */
	public static function getMysql( $dbName = 'common' )
	{
		static $mysqlObject = array();
		if( empty( $mysqlObject[ $dbName ] ) )
		{
			$mysqlConfig = & Common::getConfig( 'mysqlDb' );
			if( empty( $mysqlConfig[ $dbName ] ) )
				throw new AppException( 4 );

			$mysqlObject[ $dbName ] = new Helper_MysqlDb( $mysqlConfig[ $dbName ] );
		}
		
		return $mysqlObject[ $dbName ];
	}
    
    /**
     * 当前是否为开发环境
     * @return boolean
     */
    public static function isDev()
    {
        return self::getConfig( 'dev' );
    }
    
    /**
     * 转化编码
     * @param type $string
     * @return type
     */
    public static function convert( $string )
    {  
        //解决WINDOWS的CMD运行测试乱码问题
        $systemConfig = self::getConfig();
        
        if( $systemConfig['outputEncode'] == 'GB2312' )
        {
            return iconv( "UTF-8", "GB2312" , $string );
        }
        return $string;
    }
    
    /**
     * 自动加载类文件
     * @param string $classname
     */
    public static function autoLoad( $className )
    {
        $className = str_replace( '_' , '/' , $className );

        //在文件夹搜索
        if( file_exists( ROOT . "/{$className}.php" ) )
        {
            include_once( ROOT . "/{$className}.php" );
            return ;
        }
        
        if( file_exists( TEST_MOD_DIR . "/{$className}.php" ) )
        {
            include_once( TEST_MOD_DIR . "/{$className}.php" );
            return ;
        }
        
        if( file_exists( TEST_TEST_DIR . "/{$className}.php" ) )
        {
            include_once( TEST_TEST_DIR . "/{$className}.php" );
            return ;
        }
        
        if( file_exists( SRC_MOD_DIR . "/{$className}.php" ) )
        {
            include_once( SRC_MOD_DIR . "/{$className}.php" );
            return ;
        }
        
        if( file_exists( SRC_THIRD_DIR . "/{$className}.php" ) )
        {
            include_once( SRC_THIRD_DIR . "/{$className}.php" );
            return ;
        }
        
        if( file_exists( SRC_CORE_DIR . "/{$className}.php" ) )
        {
            include_once( SRC_CORE_DIR . "/{$className}.php" );
            return ;
        }
        
    }
    
    /**
     * 自动载入方法注册
     */
    public static function registerAutoLoad()
    {
        spl_autoload_register( array( 'Common' , 'autoLoad' ) ); 
    }
}